using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.Data.Filtering;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using ChuanPlus.DAO;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.Xpo;
namespace ChuanPlus.FormControl
{
    public partial class ControlNewInvoice : DevExpress.XtraEditors.XtraUserControl
    {
        
        List<BuyInProduct> lstBuyInProducts = new List<BuyInProduct>();
        List<PreviousPrice> lst = null;
        Users currentUser = null;
        public ControlNewInvoice(Users currentUser)
        {
            InitializeComponent();
            
            comboSupplier.Properties.Items.AddRange(xpColSupplier);
            gridBottom.DataSource = lstBuyInProducts;
            this.currentUser = currentUser;
        }

        private void comboSupplier_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboSupplier.SelectedIndex != -1)
            {
            	Supplier sup = comboSupplier.SelectedItem as Supplier;
                memoAddress.Text = sup.SupplierAdd;
                textPhone.Text = sup.SupplierPhone;
                textFax.Text = sup.SupplierFax;
            }
        }

       

        private void textFilter_EditValueChanged(object sender, EventArgs e)
        {            
            CriteriaOperator opeLeft = new BinaryOperator(new OperandProperty("ID.ItemCode"), new OperandValue("%" + textFilter.Text + "%"), BinaryOperatorType.Like);
            CriteriaOperator opeRight = new BinaryOperator(new OperandProperty("ID.Description"), new OperandValue("%" + textFilter.Text + "%"), BinaryOperatorType.Like);
            CriteriaOperator filter = new GroupOperator(GroupOperatorType.Or, new CriteriaOperator[2] { opeLeft, opeRight });            
            xpColItemList.Filter = filter;
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            // Checks whether an end-used has double clicked the row indicator.
            GridHitInfo hi = gridView1.CalcHitInfo(gridTop.PointToClient(MousePosition));
            if (!hi.InRow) return;
            // Retrieves the persistent object that corresponds to the currently focused grid row.
            int DSRowIndex = gridView1.Columns.View.GetDataSourceRowIndex(gridView1.FocusedRowHandle);
            Stock currentProduct = xpColItemList[DSRowIndex] as Stock;
            if (currentProduct.warehouseID.warehouseId == 1)     // restock to office is not allowed
            {
                return;
            }
            // check if user select same distributor in one invoice
            if (lstBuyInProducts.Count > 0)
            {
                string disName = currentProduct.ID.DistributorID.DistributorName;
                if (disName != lstBuyInProducts[0].Distributor)
                {
                    lblMessage.Text = "Current distributor in Invoice is " + lstBuyInProducts[0].Distributor;
                    lblMessage.Text += ", Cannot add " + disName + " to Invoice";
                    return;
                }
                else
                    lblMessage.Text = "";
            }
            BuyInProduct p = new BuyInProduct(currentProduct, currentProduct.ID.ItemCode, currentProduct.ID.Description, 0, 1,currentProduct.ID.DistributorID.DistributorName);
            if (lstBuyInProducts.Contains(p))     // do not add to list if product is added
                return;

            lstBuyInProducts.Add(p);
            gridBottom.RefreshDataSource();
        }

        #region Validation
        public bool validation()
        {
            if (textInvoiceNo.Text == "")
            {
                MessageBox.Show("Please enter invoice no","Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
                textInvoiceNo.Focus(); return false;
            }
            if (comboSupplier.Text == comboSupplier.Properties.NullText)
            {
                MessageBox.Show("Please select a supplier", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                comboSupplier.Focus(); return false;
            }
            if (dateInvoice.Text == "")
            {
                MessageBox.Show("Please pick a invoice date", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                dateInvoice.Focus(); return false; 
            }
            if (textContractNo.Text == "")
            {
                MessageBox.Show("Please enter contract no", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                textContractNo.Focus(); return false; 
            }
            if (comboDelivery.Text == "")
            {
                MessageBox.Show("Please select Term of Delivery", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                comboDelivery.Focus(); return false;
            }
            if (comboPayment.Text == "")
            {
                MessageBox.Show("Please select Term of Payment", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                comboPayment.Focus(); return false;
            }
            if (dateExpire.Text =="")
            {
                MessageBox.Show("Please pick a Expire Date", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                dateExpire.Focus(); return false;
            }
            if (lstBuyInProducts.Count <= 0)
            {
                MessageBox.Show("Please select buying products", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (!priceValidation())
                return false;
            return true;
        }
        private void dateExpire_Properties_Validating(object sender, CancelEventArgs e)
        {
            DateTime expireDate = dateExpire.DateTime;
            DateTime invoiceDate = dateInvoice.DateTime;
            if (DateTime.Compare(expireDate, invoiceDate) == -1)
            {
                e.Cancel = true;
                dateExpire.ErrorText = "Expire date must greater than invoice date";
            }
        }
        private void textInvoiceNo_Properties_Validating(object sender, CancelEventArgs e)
        {
            if (textInvoiceNo.Text == "")
            {
                e.Cancel = true;
            }
        }
        private bool priceValidation()
        {
            foreach (BuyInProduct item in lstBuyInProducts)
            {
                if (item.UnitPrice == 0)
                {
                    MessageBox.Show("Please enter unit price for buy item", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            return true;
        }
        private void comboSupplier_Validating(object sender, CancelEventArgs e)
        {
            Supplier s = comboSupplier.SelectedItem as Supplier;
            if (s == null)
            {
                e.Cancel = true;
                comboSupplier.ErrorText = "Supplier " + comboSupplier.Text + " does not exsit";
            }
        }
        
        private void textInvoiceNo_Validating(object sender, CancelEventArgs e)
        {
            if (textInvoiceNo.Text.Trim() == "")
            {
                e.Cancel = true;
                textInvoiceNo.ErrorText = "Please enter invoice no";
            }
            if (InvoiceDAO.GetInvoiceByID(textInvoiceNo.Text) != null)
            {
                e.Cancel = true;
                textInvoiceNo.ErrorText = "This invoice ID is used";
            }
        }
        #endregion
        private void gridView2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                // Retrieves the persistent object that corresponds to the currently focused grid row.
                int DSRowIndex = gridView2.Columns.View.GetDataSourceRowIndex(gridView2.FocusedRowHandle);
                lstBuyInProducts.RemoveAt(DSRowIndex);     // do not add to list if product is added      
                gridBottom.RefreshDataSource();
            }
        }

        private void toolTipController1_GetActiveObjectInfo(object sender, DevExpress.Utils.ToolTipControllerGetActiveObjectInfoEventArgs e)
        {
            if (e.SelectedControl != gridBottom) return;
            ToolTipControlInfo info = null;
            try
            {
                GridView view = gridBottom.GetViewAt(e.ControlMousePosition) as GridView;
                if (view == null) return;
                GridHitInfo hi = view.CalcHitInfo(e.ControlMousePosition);
                if (hi.InRowCell)
                {
                    if (hi.Column.FieldName == "UnitPrice" && comboSupplier.SelectedItem != null)
                    {
                        info = GetToolTip(view, hi.RowHandle, hi.Column);
                    }
                }
            }
            finally
            {
                e.Info = info;

            }
        }
        private ToolTipControlInfo GetToolTip(GridView view, int rowHandle, DevExpress.XtraGrid.Columns.GridColumn column)
        {
            string content = "";
            string title = "";
            int DSRowIndex = view.GetDataSourceRowIndex(rowHandle);
            BuyInProduct purPro = lstBuyInProducts[DSRowIndex];
            lst = InvoiceDAO.GetPreviousBuyPrice(comboSupplier.Text, purPro.stock.ID.ID); // query db and get previous price for this customer, this product
            foreach (PreviousPrice item in lst)
            {
                content += item.OrderDate.ToString("dd/MM/yyyy") + "\t";
                content += String.Format("{0:n}", item.UnitPrice) + "\n";
            }
            title = comboSupplier.Text + " - " + purPro.Description;
            ToolTipControlInfo info = new ToolTipControlInfo(new CellToolTipInfo(rowHandle, column, "cell"), content);
            SuperToolTipSetupArgs args = new SuperToolTipSetupArgs();
            args.Title.Text = title;
            args.Contents.Text = content;
            SuperToolTip superTooltip = new SuperToolTip();
            superTooltip.Setup(args);
            info.SuperTip = superTooltip;
            return info;
        }
        
        private void buttonInsert_Click(object sender, EventArgs e)
        {
            if (!validation()) return;
            DialogResult result =  MessageBox.Show("Are you sure want to create a new invoice?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            if(result.ToString() == "Yes")
            {
                double total = Convert.ToDouble(gridView2.Columns["Total"].SummaryItem.SummaryValue);
                Invoice invoice = new Invoice(Session.DefaultSession, textInvoiceNo.Text, comboSupplier.SelectedItem as Supplier, dateInvoice.DateTime, textContractNo.Text, comboDelivery.SelectedText, comboPayment.SelectedText, dateExpire.DateTime, textBankAccount.Text, textRemitTo.Text, total, currentUser, null,"H");                
                foreach (BuyInProduct item in lstBuyInProducts)
                {
                    InvoiceDetails details = new InvoiceDetails(Session.DefaultSession, invoice, item.stock, item.qty, item.UnitPrice);
                    invoice.InvoiceDetails.Add(details);
                }
                invoice.Save();               
                ResetControl();
            }
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            ResetControl();
        }
        private void ResetControl()
        {
            textInvoiceNo.Text = "";
            comboSupplier.SelectedItem = null;
            memoAddress.Text = "";
            textPhone.Text = "";
            textFax.Text = "";
            dateInvoice.Text = "";
            textContractNo.Text = "";
            comboDelivery.Text = "";
            comboPayment.Text = "";
            dateExpire.Text = "";
            textBankAccount.Text = "";
            textRemitTo.Text = "";
            lstBuyInProducts.Clear();
            gridBottom.RefreshDataSource();
        }

        private void ControlNewInvoice_Load(object sender, EventArgs e)
        {

        }

        

        private void gridView1_RowStyle(object sender, RowStyleEventArgs e)
        {
            int DSRowIndex = gridView1.GetDataSourceRowIndex(e.RowHandle);
            if (DSRowIndex >= 0)
            {
                Stock s = xpColItemList[DSRowIndex] as Stock;
                if (s.warehouseID.warehouseId == 1)
                    e.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192)))));

            }
        }

      
    }
    public class BuyInProduct
    {
        private Stock _Stock;
        public Stock stock
        {
            get { return _Stock; }
            set { _Stock = value; }
        }
        private string _ItemCode;
        public string ItemCode
        {
            get { return _ItemCode; }
            set { _ItemCode = value; }
        }
        private string _Description;
        public string Description
        {
            get { return _Description; }
            set { _Description = value; }
        }
        private double _UnitPrice;
        public double UnitPrice
        {
            get { return _UnitPrice; }
            set { _UnitPrice = value;
            _total = qty * UnitPrice;
                    }
        }
        private double _Qty;
        public double qty
        {
            get { return _Qty; }
            set
            {
                _Qty = value;
                _total = qty * UnitPrice;
            }
        }      
        
        private double _total;
        public double Total
        {
            get { return _total; }
            set { _total = value; }
        }
        private string _Distributor;
        public string Distributor
        {
            get { return _Distributor; }
            set { _Distributor = value; }
        }
        public override bool Equals(Object b)
        {
            bool result = true;
            if (b == null) result = false;
            try
            {
                BuyInProduct p = (BuyInProduct)b;
                if (p.stock.ID.ID == this.stock.ID.ID)
                    result = true;
                else
                    result = false;
            }
            catch
            {
                result = false;
            }
            return result;
        }
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
        /// <summary>
        /// Initializes a new instance of the PurchaseProduct class.
        /// </summary>
        /// <param name="product"></param>
        /// <param name="itemCode"></param>
        /// <param name="description"></param>
        /// <param name="unitPrice"></param>
        /// <param name="qty"></param>        
        public BuyInProduct(Stock stock, string itemCode, string description, double unitPrice, double qty, string distributor)
        {
            _Stock = stock;
            _ItemCode = itemCode;
            _Description = description;
            _UnitPrice = unitPrice;
            this.qty = qty;
            _Distributor = distributor;
        }

    }
}
